import router from '@/router'
import {
  ElMessageBox,
} from 'element-plus'
import {
  login,
  logout,
  getInfo,
  getRoleMenu
} from '@/api/login'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  isHttp,
  isEmpty
} from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore(
  'user', {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      nickName: '',
      avatar: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        const phone = userInfo.phone.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        return new Promise((resolve, reject) => {
          login(phone, password, code, uuid).then(res => {
            setToken(res.data.accessToken)
            this.token = res.data.accessToken

            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(async res => {
            const user = res.data
            let avatar = user.avatar || ""
            if (!isHttp(avatar)) {
              avatar = (isEmpty(avatar)) ? defAva : import.meta.env.VITE_APP_BASE_API + avatar
            }

            if (res.roles && res.roles.length > 0) {
              this.roles = res.roles
            } else {
              this.roles = ['ROLE_DEFAULT']
            }

            this.id = user.userId
            this.name = user.phone
            this.nickName = user.name
            this.avatar = avatar

            // 根据角色 ID 获取菜单及按钮权限
            if (user.belongToRole && user.belongToRole.length > 0) {
              const roleId = user.belongToRole[0].id
              try {
                const menuRes = await getRoleMenu(roleId)
                this.permissions = extractButtonPerms(menuRes.data.menus || [])
                
              } catch (e) {
                console.error('获取按钮权限失败:', e)
                this.permissions = []
              }
            }

            /* 初始密码提示 */
            if (res.isDefaultModifyPwd) {
              ElMessageBox.confirm('您的密码还是初始密码，请修改密码！', '安全提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                router.push({
                  name: 'Profile',
                  params: {
                    activeTab: 'resetPwd'
                  }
                })
              }).catch(() => {})
            }

            /* 过期密码提示 */
            if (!res.isDefaultModifyPwd && res.isPasswordExpired) {
              ElMessageBox.confirm('您的密码已过期，请尽快修改密码！', '安全提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                router.push({
                  name: 'Profile',
                  params: {
                    activeTab: 'resetPwd'
                  }
                })
              }).catch(() => {})
            }

            resolve(res)
          }).catch(error => reject(error))
        })
      },
      // 退出系统
      logOut() {
        console.log('退出系统');
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })


      }
    }
  })

function extractButtonPerms(menus) {
  const perms = []
  menus.forEach(item => {
    if (item.menuType === 'button' && item.perms) {
      perms.push(item.perms)
    }
    if (item.children && item.children.length > 0) {
      perms.push(...extractButtonPerms(item.children))
    }
  })
  return perms
}
export default useUserStore